package com.springboot.util.http;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zyj
 * @description
 * @date 2019/5/10 11:08
 **/
@Component
@Slf4j
public class ResponseUtil {

    private HttpServletResponse getResponse(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getResponse();
    }

    public HttpServletRequest getRequest(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }

    public void respJson(JSONObject jsonObj){
        HttpServletResponse response =  getResponse();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null ;
        try{
            out = response.getWriter();
            out.append(jsonObj.toString());
            out.flush();
            out.close();
        } catch (Exception e){
            e.printStackTrace();
            log.error("response 返回数据失败：", e);
            try {
                response.sendError(500);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    public void respErrorJson(String code){
        this.respErrorDataJson(code, "");
    }

    public void respErrorJsonMsg(String code, String msg){
        this.respErrorDataJson(code, msg, "");
    }

    public void respErrorDataJson(String code, String msg, Object data){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("msg", msg);
        jsonObject.put("data", data);
        respJson(jsonObject);

    }

    public void respErrorDataJson(String code, Object data){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("msg", "请求失败");
        jsonObject.put("data", data);
        respJson(jsonObject);

    }

    public void respSuccessDataJson(Object data){
        respSuccessDataJson("200", data);

    }

    public void respSuccessDataJson(String code, Object data){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("msg", "请求成功");
        jsonObject.put("data", data);
        respJson(jsonObject);

    }

}
